<template>
    <ex-dialog width="1200px" class="ex-diolog" title="发放积分" :visible="visible" @closeDialog="handleClose">
        <div class="listBox_head">
            <el-upload class="upload-demo" :action="fileaction" :headers="headers" :data="fileData" :limit="1"
                :on-success="importStore" :show-file-list="false" :file-list="fileList" ref="elUpload" :on-progress="onProgress" v-loading="uploadLoading"l>
                <el-button type="primary">导入店铺</el-button>
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
            <!-- <el-button size="mini" type="primary" @click="importStore">导入店铺</el-button> -->
            <el-button type="primary" @click="downloadTemplate">下载导入模板</el-button>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="130px">
            <el-form-item label="添加店铺:" prop="">
                <el-select v-model="form.shopItem" placeholder="可搜索下拉多选店铺" value-key="merchantId" filterable multiple
                    style="width: 550px;">
                    <el-option v-for="item in shopList" :key="item.merchantId" :label="item.shopName" :value="item"
                        :disabled="item.disabled"></el-option>
                </el-select>
                <el-button type="primary" style="margin-left: 20px" @click="confirmAddition">确认添加</el-button>
            </el-form-item>
            <el-table :data="form.tabelList" v-loading="loading" element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.6)" element-loading-text="加载中" stripe border >
                <el-table-column label="序号" align="center" type="index" width="64px" />
                <el-table-column label="商户编号" align="center" prop="merchantId" :show-overflow-tooltip="true" />
                <el-table-column label="店铺名称" align="center" prop="shopName" :show-overflow-tooltip="true" />
                <el-table-column label="商户账号名称" align="center" prop="merchantName" :show-overflow-tooltip="true" />
                <el-table-column label="发放积分" align="center" prop="issueAmount" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <el-form-item label="" :prop="'tabelList.' + scope.$index + '.issueAmount'"
                            :rules="rules.issueAmount" label-width="0" v-if="scope.row.isSave" >
                            <el-input type="text" v-model="scope.row.issueAmount" placeholder="请输入" ></el-input>
                        </el-form-item>
                        <div v-else>{{ scope.row.issueAmount }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" @click="handleSave(scope.$index, scope.row)"
                            v-if="scope.row.isSave">保存</el-button>
                        <el-button size="mini" type="text" @click="handleEdit(scope.$index, scope.row)"
                            v-if="!scope.row.isSave">编辑</el-button>
                        <el-button size="mini" type="text" @click="handleDel(scope.$index, scope.row)"
                            v-if="!scope.row.isSave">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm()" :loading="sumitLoading">执行发放</el-button>
            <el-button @click="handleClose">取 消</el-button>
        </div>
    </ex-dialog>
</template>

<script>
import {
    assetApplyIssueInfoList,
    assetApplySelectShopList,
    assetApplyIssueExecute,
    assetApplyDelIssue,
    assetApplyAddIssue,
    assetApplyEditIssue
} from "@/api/integralOperation/integralAirdrop";
import { getToken } from "@/utils/auth";
import ExportExcelButton from "@/components/ExportExcelButton/index";
export default {
    // dicts: ['asset_card_type'],
    name: "Dialog",
    components: {
        ExportExcelButton
    },
    props: {
        visible: Boolean,
        id: String,
    },
    data() {
        var checkUseable = (rule, value, callback) => {
            var reg = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
            if (value === '') {
                callback(new Error('请输入发放积分'));
            } else if (!reg.test(value) || value == '0.00' || value == '0.0') {
                callback(new Error('请输入大于0的数值，最多保留两位小数'));
            } else {
                callback()
            }
        };
        return {
            sumitLoading: false,
            uploadLoading: false,
            loading: false,
            title: "打卡活动配置",
            shopList: [],
            form: {
                shopItem: '',
                tabelList: [

                ],
            },
            //导入需要的参数
            fileData: {
                applyId: '',
            },
            fileList: [],
            fileaction: process.env.VUE_APP_BASE_API + "/platform/merchant/asset/apply/issue/info/import",
            headers: {
                "X-Access-Token": getToken(),
            }, //设置上传文件请求头
            // 表单校验
            rules: {
                issueAmount: [{
                    required: true,
                    validator: checkUseable,
                    trigger: ['change', 'blur'],
                }],
            },
        };
    },
    created() {
        this.fileData.applyId = this.id
        this.getShopList()
        this.getDetailList()
    },
    methods: {
        //获取打卡活动下拉
        getShopList() {
            assetApplySelectShopList().then(res => {
                // res.result = res.result.map((item,index) => {
                //     item.issueAmount = ''
                //     item.isSave = true
                //     item.isHandleAdd = true
                //     return item
                // })
                this.shopList = res.result
            })
        },
        //获取列表
        getDetailList() {
            var data = {
                applyId: this.id,
                status: ''
            }
            assetApplyIssueInfoList(data).then(res => {
                res.result = res.result.map(item => {
                    this.$set(item, 'isSave', false)  //是否保存
                    this.$set(item, 'isHandleAdd', false) //是否是手动添加
                    return item
                })
                this.form.tabelList = this.form.tabelList.concat(res.result)
            })
        },
        //手动添加店铺
        confirmAddition() {
            if (this.form.shopItem == '') {
                this.$message.error('请选择店铺')
                return 
            } 
            let arrayList = []
            JSON.parse(JSON.stringify(this.form.shopItem)).forEach(item => {
                this.$set(item, 'isSave', true)
                this.$set(item, 'isHandleAdd', true)
                this.$set(item, 'issueAmount', '')
                this.$set(item, 'id', this.genID(12))
                arrayList.push(item)
            });
            // this.form.tabelList = [
            //     ...this.form.tabelList,
            //     ...arrayList
            // ]
            this.form.tabelList = this.form.tabelList.concat(arrayList)
            this.form.shopItem = ''
            // console.log('this.form.tabelList',this.form.tabelList)
            // this.$forceUpdate();
        },
        // 生成随机id
        genID(length){
            return Number(Math.random().toString().substr(3,length) + Date.now()).toString(36);
        },
        //取消
        handleClose(formName) {
            this.$emit('update:visible', false)
        },
        //确认
        handleConfirm() {
            this.$emit('success')
        },

        /** 执行按钮 */
        submitForm() {
            if (this.form.tabelList.length > 0) {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        var tabelList = this.form.tabelList.every((item) => {
                           return item.isSave == false
                        });
                        if (!tabelList) {
                            this.$message.error('请保存发放积分')
                        } else {
                            this.sumitLoading = true
                            assetApplyIssueExecute(this.id).then(response => {
                                setTimeout(() => {
                                    this.$message.success('执行成功');
                                    this.handleClose();
                                    this.$emit('success')
                                    this.sumitLoading = false;
                                }, 1000)
                            }).catch(() => {
                                this.sumitLoading = false;
                            });
                        }
                    }
                });
            } else {
                this.$message.error('请添加店铺')
            }

        },
        // 添加
        handleSave(index, row) {
            if (row.issueAmount == '') {
                return
                // this.$message.error('请输入发放积分')
            } else if (row.isHandleAdd) {
                this.saveData(index, row)
            } else {
                this.editData(index, row)
            }
        },
        // 编辑
        handleEdit(index, row) {
            this.form.tabelList[index].isSave = true
        },
        // 删除
        handleDel(index, row) {
            this.$confirm('是否删除', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                if (row.isHandleAdd) {
                    this.$message.success('删除成功');
                    this.form.tabelList.splice(index, 1)
                } else {
                    this.delData(index,row.id)
                }
            }).catch(() => { });
        },
        // 删除数据
        delData(index,id) {
            assetApplyDelIssue(id).then(response => {
                this.$message.success('删除成功');
                this.form.tabelList.splice(index, 1)
            }).catch(() => {

            });
        },
        // 保存数据
        saveData(index, item) {
            var data = {
                applyId: this.id,
                issueAmount: item.issueAmount,
                merchantId: item.merchantId,
            }
            assetApplyAddIssue(data).then(response => {
                this.$message.success('保存成功');
                this.form.tabelList[index].id = response.result
                this.form.tabelList[index].isSave = false
                this.form.tabelList[index].isHandleAdd = false

            }).catch(() => {
                // this.sumitLoading = false;
            });
        },
        // 编辑数据
        editData(index, item) {
            var data = {
                id: item.id,
                issueAmount: item.issueAmount,
            }
            assetApplyEditIssue(data).then(response => {
                this.$message.success('保存成功');
                this.form.tabelList[index].id = response.result
                this.form.tabelList[index].isSave = false
                this.form.tabelList[index].isHandleAdd = false
            }).catch(() => {
                this.sumitLoading = false;
            });
        },
        //下载导入模板
        downloadTemplate() {
            location.href = 'https://kayouyou-1257308601.cos.ap-guangzhou.myqcloud.com/商户发放积分导入模板.xlsx'
        },
        onProgress(res,file){
            // this.uploadLoading = true
        },
        // 导入店铺
        importStore(res, file) {
            console.log('文件', res)
            if (res.code == 200) {
                this.$message.success('导入成功');
                this.uploadLoading = false
                res.result = res.result.map(item => {
                    this.$set(item, 'isSave', false)  //是否保存
                    this.$set(item, 'isHandleAdd', false) //是否是手动添加
                    return item
                })
                this.form.tabelList = this.form.tabelList.concat(res.result)
                // this.getDetailList();
            } else {
                this.$message.error(res.message);
                this.uploadLoading = false
            }
            this.$refs.elUpload.clearFiles()
        }

    }
};

</script>

<style scoped>
.upload-demo {
    margin-right: 10px;
}

.listBox_head {
    position: absolute;
    top: 13px;
    left: 120px;
    display: flex;
    flex-direction: row;
}
</style>